package cn.livingCloud.service.impl;

import cn.livingCloud.dto.ButtonFormListDto;
import cn.livingCloud.dto.ButtonListDto;
import cn.livingCloud.entity.content.Button;
import cn.livingCloud.repository.ButtonMapper;
import cn.livingCloud.service.ButtonService;
import cn.livingCloud.service.impl.operation.ButtonFormListDtoLoader;
import cn.livingCloud.service.impl.operation.ButtonFormListDtoUpdater;
import cn.livingCloud.service.impl.operation.ButtonListDtoLoader;
import cn.livingCloud.service.impl.operation.MenuPusher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * Created by sujiantang on 2016/1/6.
 */
@Service
public class ButtonServiceImpl implements ButtonService {
    @Autowired
    private ButtonMapper mapper;
    private static final int BUTTON_NUMBER = 3;
    private static final int SUB_BUTTON_NUMBER = 5;

    @Override
    public void findButtonList(ButtonListDto listDto) {
        ButtonListDtoLoader loader = new ButtonListDtoLoader(listDto);
        loader.load();
    }

    @Override
    public void loadButtonFormDto(ButtonFormListDto formListDto) {
        ButtonFormListDtoLoader loader = new ButtonFormListDtoLoader(formListDto);
        loader.load();
    }

    @Override
    public void updateButton(ButtonFormListDto formListDto) {
        ButtonFormListDtoUpdater updater = new ButtonFormListDtoUpdater(formListDto);
        updater.update();
    }

    @Override
    public void deleteButton(String uuid) {
        Button button = mapper.findButtonByUuid(uuid);
        if (StringUtils.isEmpty(button.getParentId())) {
            mapper.deleteSubButton(uuid);
        }
        mapper.delete(uuid);
    }

    @Override
    public boolean pushMenu() {
        MenuPusher pusher = new MenuPusher();
        return pusher.push();
    }

    @Override
    public boolean checkButtonNumber(ButtonFormListDto formListDto) {
        if (StringUtils.isEmpty(formListDto.getUuid())) {
            int buttonNumber = mapper.countButton();
            if (StringUtils.isEmpty(formListDto.getParent_id()) && buttonNumber >= BUTTON_NUMBER) {
                return false;
            }
            int subButtonNumber = mapper.countSubButton(formListDto.getParent_id());
            if (subButtonNumber >= SUB_BUTTON_NUMBER) {
                return false;
            }
        }
        return true;
    }
}
